package com.kjlink.widget.monitoring.util;

import com.kjlink.common.base.vo.BooleanWithMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * @Description UDP工具类
 */
public class UDPUtil {

    private static final Logger logger = LoggerFactory.getLogger(UDPUtil.class);

    // 注意：会不会有端口一直被占用的情况？ 2：会不会有线程安全问题
    private static DatagramSocket socket;

    // 只初始化一次
    static {
        try {
            socket = new DatagramSocket();
        } catch (SocketException e) {
            logger.error("DatagramSocket init, error:{}", e);
        }
    }

    /**
     * 获取本机IP
     *
     * @return
     */
    public static String getLocalIP() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e) {
            logger.error("获取当前机器IP失败，error:", e);
        }

        return "127.0.0.1";
    }


    /**
     * 发送UDP报文
     */
    public static BooleanWithMsg send(String ip, int port, String content) {
        try {
            DatagramPacket udpSendPacket = new DatagramPacket(content.getBytes(), content.getBytes().length,
                    InetAddress.getByName(ip), port);
            socket.send(udpSendPacket);
            logger.info("UDPUtil.send success, ip:{}:{}, content:\n\t{}", ip, port, content);
            return BooleanWithMsg.success();
        } catch (Exception e) {
            logger.error("UDPUtil.send failed, ip:{}:{}, content:{}", ip, port, content, e);
            return BooleanWithMsg.fail("UDPUtil.send failed: " + e.getMessage());
        }
    }

}
